package TCPClient;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

import messangerTypes.*;


public class TCPSendWorker extends Thread
{
	private OutputStream out;
	public boolean quit = false;
	private ConcurrentLinkedQueue<MessageBase> writeQueue;
	private Semaphore sem;
	

	public TCPSendWorker(OutputStream out)
	{
		writeQueue = new ConcurrentLinkedQueue<MessageBase>();
		sem = new Semaphore(0);
		this.out = out;
	}
	
	public void write (MessageBase mb)
	{
		if(writeQueue.add(mb))
		{
			sem.release();
		}
		else
		{
			//i dont know add failed. may be the next one wont?
		}
	}
		
	@Override
	public void run()
	{
		try
		{
			ObjectOutputStream outToServer = new ObjectOutputStream (this.out);
			
			do{
				//ensures there is to deadlock
				if(sem.tryAcquire(250, TimeUnit.MILLISECONDS))
				{
					MessageBase mb = writeQueue.poll();
					
					if(mb != null)
					{
						outToServer.writeObject(mb);
					}
					else
					{
						//queue was empty !?
					}
				}
				else
				{
					
				}
			}while(!quit);
			
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
